<template>
  <page-card title="机构管理">
    <div>
      <slot name="searchWrapper" />
      <a-form v-if="!$slots.searchWrapper"
              layout="inline">
        <a-row style="height:56px">
          <a-col :span="8">
            <a-space>
              <slot name="buttons" />
              <template v-if="!$slots.buttons">
                <a-button type="primary"
                          v-if="hasPermission('add')"
                          @click="addTop(0)">
                  添加根级
                </a-button>
                <a-tooltip placement="top" :mouseEnterDelay="0.4">
                  <template slot="title">
                    <span>消息通知的分组发送</span>
                  </template>
                    <a-button type="primary"
                              @click="addGroup(0)">
                      机构分组管理
                    </a-button>
                </a-tooltip>
                <a-tooltip placement="top" :mouseEnterDelay="0.4">
                  <template slot="title">
                    <span>机构数据编码修正</span>
                  </template>
                  <a-button type="primary"
                            @click="initParentName()">
                    初始化上级机构名称
                  </a-button>
                </a-tooltip>
              </template>
            </a-space>
          </a-col>
          <a-col :span="12"></a-col>
          <a-col :span="4">
            <a-input-search placeholder="机构名称、编码"
                            v-model="unitNameOrCode"
                            @search="findUnit"
                            style="min-width:200px;width: 100%"
                            allow-clear />
          </a-col>
        </a-row>
      </a-form>
      <a-form layout="inline">
        <a-row>

        </a-row>
      </a-form>
    </div>
    <slot name="table" />
    <a-table v-if="!$slots.table"
             ref="unitTableTree"
             :pagination="isPaginationList ? paginationList : false"
             :rowKey="(record, index) => record.id"
             :data-source="unitTableTreeData"
             :expandedRowKeys="expandedRowKeys"
             @change="unitHandleTableChange"
             @expand="expand"
             :columns="columns">

      <span slot="type"
            slot-scope="text,record">
        <span v-if="record.type == '1' ">分类</span>
        <span v-if="record.type == '2' ">单位</span>
        <span v-if="record.type == '3' ">内部机构</span>

      </span>

      <span slot="operation"
            slot-scope="text, record">
        <Zoptionitem :optiondata="optiondata"
                     :record="record">
        </Zoptionitem>
      </span>

    </a-table>
    <!--
    <VirtualTable row-key="id"
                  :scroll="{ 'y': 540 }"
                  :columns="columns2"
                  v-bind="state"
                  @expand-change="expandChange"
                  :data-source="unitTableTreeData">

      <span slot="type"
            slot-scope="text,record">
        <span v-if="record.type == '1' ">分类</span>
        <span v-if="record.type == '2' ">单位</span>
        <span v-if="record.type == '3' ">内部机构</span>
      </span>

      <span slot="operation"
            slot-scope="text, record">
        <Zoptionitem :optiondata="optiondata"
                     :record="record">
        </Zoptionitem>
      </span>
    </VirtualTable>
    -->
    <a-modal title="机构移动"
             :visible="move.visible"
             :selectedKeys="move.selectedKeys"
             @ok="moveHandleOk"
             @cancel="moveHandleCancel">
      <a-tree style="overflow-y:auto;max-height: 500px"
              ref="unitTree"
              :showIcon="true"
              @select="moveSelect"
              :expandedKeys="unit.expandedKeys"
              @expand="moveExpand"
              :tree-data="unit.treeData">
        <a-icon slot="switcherIcon"
                type="caret-down" />
        <a-icon slot="clazz"
                type="appstore" />
        <a-icon slot="unit"
                type="home" />
        <a-icon slot="dept"
                type="bank" />
        <template #title="item">
          <a-dropdown :trigger="['contextmenu']">
            <span v-if="item.treeTitle.indexOf(unit.searchValue) > -1">
              {{ item.treeTitle.substr(0, item.treeTitle.indexOf(unit.searchValue)) }}
              <span style="color: #f50">{{ unit.searchValue }}</span>
              {{ item.treeTitle.substr(item.treeTitle.indexOf(unit.searchValue) + unit.searchValue.length) }}
            </span>
            <span v-else>{{ item.treeTitle }}</span>
          </a-dropdown>
        </template>
      </a-tree>
    </a-modal>
    <a-modal title="机构排序"
             :visible="order.visible"
             @ok="orderHandleOk"
             @cancel="orderHandleCancel">
      <a-tree style="overflow-y:auto;max-height: 500px"
              ref="unitTree"
              :showIcon="true"
              :expandedKeys="order.unit.expandedKeys"
              @expand="orderExpand"
              @drop="drop"
              :draggable="order.unit.draggable"
              :tree-data="order.unit.treeData">
        <a-icon slot="switcherIcon"
                type="caret-down" />
        <a-icon slot="clazz"
                type="appstore" />
        <a-icon slot="unit"
                type="home" />
        <a-icon slot="dept"
                type="bank" />
        <template #title="item">
          <span>{{ item.treeTitle }}</span>
        </template>
      </a-tree>
    </a-modal>
    <sync @cancel="cancel"
          :visible="syncVisible"
          :mediaType="mediaType"
          :syncType="syncType"
          :deptId="deptId"
          :mediaId="mediaId"></sync>

  </page-card>
</template>

<script>
import { FONT_COLOR } from '../../constants'
import { page, startAndStopState, getUnitTreeNodesByParentId, initBelongs, queryPageTable, unitMoveTree, unitMove, unitOrderTree, unitOrder } from '../../api/unit/index'
import Zoptionitem from '../../components/z-column/Zoptionitem'

import ArrayUtil from '@zh/common-utils/utils/array'
import Sync from '../sync/Sync'
export default {
  props: {
    optiondataProps: {
      type: Array,
      require: true,
      default: null
    }
  },
  components: { Zoptionitem, Sync },
  data () {
    return {
      move: {
        visible: false,
        unitId: '',
        selectedKeys: []
      },
      unit: {
        unitId: '',
        treeData: [],
        expandedKeys: [],
        selectedKeys: [],
        dataList: [],
        searchValue: ''
      },
      order: {
        unitId: '',
        visible: false,
        unit: {
          expandedKeys: [],
          treeData: [],
          draggable: true
        }
      },
      expandedNodes: [{ id: null }],
      unitNameOrCode: '', // 搜索条件
      state: {
        bordered: false,
        size: 'default',
        expandable: {
          defaultExpandAllRows: false,
          expandedRowRender (record) {
          },
          expandDepth: 1,
          indentSize: 20
        },
        title: undefined,
        showHeader: true,
        ellipsis: true,
        rowHeight: 55,
        footer: undefined,
        useVirtual: true,
        xScroll: undefined,
        yScroll: !!scroll.y,
        rowSelection: {},
        tableLayout: 'fixed'
      },
      optiondata: [
        {
          type: 'text',
          fn: this.add,
          title: '新增',
          show: this.hasPermission('add')
        },
        {
          type: 'text',
          fn: this.edit,
          title: '编辑',
          show: this.hasPermission('edit')
        },
        {
          type: 'text',
          fn: this.moveUnit,
          title: '移动',
          show: this.hasPermission('move')
        },
        {
          type: 'text',
          fn: this.moveOrder,
          title: '排序',
          show: this.hasPermission('order')
        },
        {
          type: 'text',
          fn: this.syncfn,
          title: '同步',
          show: this.hasPermission('synclog')
          // && this.syncOff
        },
        {
          type: 'text',
          fn: this.syncLog,
          title: '同步记录',
          show: this.hasPermission('synclog') && this.syncOff
        },
        {
          type: 'confirm',
          fn: this.startState,
          title: '启用',
          show: this.hasPermission('stop'),
          showcondition: ['state == 0'],
          confirm: {
            title: '确定启用该机构吗？',
            okfn: this.startState,
            cancelfn: this.cancelChangeState
          }
        },
        {
          type: 'confirm',
          fn: this.stopState,
          title: '停用',
          show: this.hasPermission('stop'),
          showcondition: ['state == 1'],
          confirm: {
            title: '确定停用该机构吗？',
            okfn: this.stopState,
            cancelfn: this.cancelChangeState
          }
        }
      ],
      syncOff: false,
      syncVisible: false,
      mediaType: '1',
      deptId: '',
      syncType: '',
      mediaId: '',
      unitTableTreeData: [],
      nodeMap: {},
      fontColor: FONT_COLOR,
      columns: [
        {
          title: '机构名称',
          dataIndex: 'name',
          align: 'left',
          ellipsis: true,
          width: '30%'
        },
        {
          title: '机构全称',
          dataIndex: 'fullName',
          align: 'left',
          ellipsis: true
        },
        {
          title: '机构类型',
          dataIndex: 'type',
          align: 'center',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '排序号',
          dataIndex: 'orderNo',
          align: 'center',
          width: 150
        }
      ],
      columns2: [
        {
          expandable: true,
          label: '机构名称',
          prop: 'name',
          align: 'left',
          ellipsis: true
        },
        {
          label: '机构全称',
          prop: 'fullName',
          align: 'left',
          ellipsis: true
        },
        {
          label: '机构类型',
          prop: 'type',
          align: 'center',
          scopedSlots: { customRender: 'type' }
        },
        {
          label: '排序号',
          prop: 'orderNo',
          align: 'center',
          width: 150
        }
      ],
      isPaginationList: false,
      paginationList: {
        current: 1,
        total: 0,
        // 默认每页显示10条数据
        pageSize: 10,
        showSizeChanger: true,
        // 修改每页显示条数
        pageSizeOptions: ['10', '20', '50', '100'],
        // 总数据数量
        showTotal: (total) => `共 ${total} 条数据`
      }
    }
  },
  computed: {
    expandedRowKeys () {
      return this.expandedNodes.map(i => i.id)
    }
  },
  beforeCreate () {
    this.syncOff = this.$store.getAppConfig('_syncOff')!==undefined && this.$store.getAppConfig('_syncOff') == 1
  },
  created () {
    if (this.optiondataProps) {
      this.optiondata = this.optiondataProps
    }

    if (this.hasPermissions('edit', 'add', 'stop')) {
      this.columns.push({
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        scopedSlots: { customRender: 'operation' },
        width: '15%'
      })
      this.columns2.push({
        label: '操作',
        prop: 'operation',
        align: 'center',
        scopedSlots: { customRender: 'operation' },
        width: 200
      })
    }
    // 未重写table并且未配置路由保持，调用默认加载列表数据接口
    // !this.$route.meta.keepAlive && !this.$slots.table && this.load()
  },
  activated () {
    // 未重写table并且配置了路由保持，调用默认加载列表数据接口
    this.$route.meta.keepAlive && !this.$slots.table && this.load()
  },
  methods: {
    findUnit () {
      if (!this.unitNameOrCode) {
        this.load()
        this.isPaginationList = false
        return
      }
      let pagination = {}
      pagination.currPage = this.paginationList.current
      pagination.pageSize = this.paginationList.pageSize
      queryPageTable({ name: this.unitNameOrCode, ...pagination }).then(res => {
        this.isPaginationList = true
        this.paginationList.current = res.currPage
        this.paginationList.total = res.totalCount
        this.paginationList.pageSize = res.pageSize
        this.unitTableTreeData = res.list
        this.nodeMap = {}
        res.list.map(i => {
          this.nodeMap[i.id] = { ...i }
        })
      })
    },
    unitHandleTableChange (pagination, filters, sorter) {
      this.paginationList = pagination
      this.findUnit()
    },
    initParentName () {
      initBelongs(null).then((res) => {
        // this.message.success('初始化成功')
      })
    },
    load () {
      getUnitTreeNodesByParentId(this.expandedNodes).then((response) => {
        const { nodeList, nodeMap } = ArrayUtil.toTree(response, 'id', 'parentId')
        this.unitTableTreeData = nodeList
        this.nodeMap = nodeMap
      })
    },
    expandChange (record, state, expandedRowKeys, event) { },
    expand (expanded, node) {
      // var xx = this.expandedNodes
      if (expanded) {
        if (!node.children || node.children.length == 0) {
          getUnitTreeNodesByParentId([{ id: node.id }]).then((response) => {
            response.length && this.addExpandedNodes(node)
            node.children = response
            response.map(i => {
              this.nodeMap[i.id] = { ...i }
            })
          })
        } else {
          this.addExpandedNodes(node)
        }
      } else {
        this.collapsedNode(this.getExpandedNode(node.id))
        // this.expandedNodes.every((i) => {
        //   if (i.id == node.id) {
        //     this.collapsedNode(i)
        //     // this.expandedNodes.splice(this.expandedNodes.indexOf(i), 1)
        //     return false
        //   }
        //   return true
        // })
      }
    },
    addExpandedNodes (treeNode) {
      let node = this.getExpandedNode(treeNode.id)
      if (node === undefined) {
        node = { id: treeNode.id, children: [] }
        this.expandedNodes.push(node)
      }
      if (treeNode.parentId) {
        const expandedParentNode = this.getExpandedNode(treeNode.parentId)
        if (expandedParentNode) {
          expandedParentNode.children.push(node)
        }
      }
    },
    getExpandedNode (id) {
      return this.expandedNodes.find(i => {
        return i.id == id
      })
    },
    collapsedNode (node) {
      if (node.children) {
        node.children.map(childNode => {
          this.collapsedNode(childNode)
        })
      }
      this.expandedNodes.splice(this.expandedNodes.indexOf(node), 1)
    },
    add (record) {
      this.$router.push({
        path: '/unit/add',
        query: {
          topId: record.id
        }
      })
    },
    addTop (topId) {
      this.$router.push({
        path: '/unit/add',
        query: {
          topId: 0
        }
      })
    },
    edit (record) {
      this.$router.push({
        path: '/unit/edit',
        query: {
          id: record.id
        }
      })
    },
    cancel () {
      this.syncVisible = false
    },
    syncfn (record) {
      this.syncVisible = true
      this.mediaId = record.id
      this.deptId = record.id
      this.syncType = '4'
    },
    syncLog (record) {
      this.$router.push({
        path: '/sync/list/detail',
        query: {
          mediaId: record.id,
          mediaType: '1'
        }
      })
    },
    startState (recode) {
      let checked = true
      const stopName = checked ? '启用' : '停用'
      if (recode.state == '1') {
        this.message.info('已启用')
        return
      }

      startAndStopState(checked, recode.id).then((res) => {
        // this.message.info(stopName + '成功')
        this.load()
        this.expandedNodes = []
        this.syncOff && this.syncfn(recode)
      })
    },
    stopState (recode) {
      let checked = false
      const stopName = checked ? '启用' : '停用'
      if (recode.state == '0') {
        this.message.info('已停用')
        return
      }
      startAndStopState(checked, recode.id).then((res) => {
        // this.message.info(stopName + '成功')
        this.load()
        this.expandedNodes = []
        this.syncOff && this.syncfn(recode)
      })
    },
    cancelSync (e) {
      this.load()
    },
    cancelChangeState (e) { },
    // 组织机构分组
    addGroup (topId) {
      this.$router.push({
        path: '/unit/group'
      })
    },
    moveUnit (record) {
      this.move.unitId = record.id
      this.unit.treeData = []
      this.move.selectedKeys = []
      this.unit.expandedKeys = []
      this.initUnitTree()
      this.move.visible = true
    },
    initUnitTree () {
      unitMoveTree({ topId: 0, unitId: this.move.unitId }).then((response) => {
        if (response.length == 0) {
          this.message.warn('无可移动机构')
        }
        this.unit.treeData = response
      })
    },
    moveHandleOk (e) {
      this.move.visible = false
      if (this.move.selectedKeys.length > 0) {
        unitMove({ unitId: this.move.unitId, moveUnitId: this.move.selectedKeys[0] }).then(res => {
          // this.message.success('保存成功')
          this.load()
        })
      }
    },
    moveHandleCancel (e) {
      this.move.visible = false
    },
    moveSelect (selectedKeys) {
      this.move.selectedKeys = selectedKeys
    },
    moveExpand (expanded, node) {
      this.unit.expandedKeys = expanded
    },
    moveOrder (record) {
      this.initOrderTree(record.id)
    },
    initOrderTree (unitId) {
      unitOrderTree({ id: unitId }).then((res) => {
        if (!res || res[0].children.length == 0) {
          this.message.warn('无节点可排序')
        } else {
          this.order.unitId = unitId
          this.order.visible = true
          res.forEach(item => {
            if (item.id == unitId) {
              item.disabled = true
            }
          })
          this.order.unit.treeData = res
          this.order.unit.expandedKeys = [unitId]
        }
      })
    },
    orderExpand (expanded, node) {
      this.order.unit.expandedKeys = expanded
    },
    orderHandleOk () {
      unitOrder(this.order.unit.treeData[0].children).then((res) => {
        // this.message.success('保存成功')
        this.order.visible = false
        this.load()
      })
    },
    orderHandleCancel (e) {
      this.order.visible = false
    },
    drop (info, node, dragNode, dragNodesKeys) {
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      if (this.order.unitId == dropKey) {
        return
      }
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.key === key) {
            return callback(item, index, arr)
          }
          if (item.children) {
            return loop(item.children, key, callback)
          }
        })
      }
      const data = [...this.order.unit.treeData]
      let dragObj

      if (info.dropToGap) {
        loop(data, dragKey, (item, index, arr) => {
          arr.splice(index, 1)
          dragObj = item
        })
        let ar
        let i
        loop(data, dropKey, (item, index, arr) => {
          ar = arr
          i = index
        })
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj)
        } else {
          ar.splice(i + 1, 0, dragObj)
        }
      }
      this.order.unit.treeData = data
    }
  }
}
</script>

<style scoped>
</style>
